package com.core.utils;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class DictKit {
	
	public static final String dictCache = "dictCache";
	
	public static Page<? extends Model> replaceDict(Page<? extends Model> page, String[] keys, String[] newKeys, Class[] dictClasses) {
		List<Model> rows = (List<Model>) page.getList();
		int length =keys.length;
		for (int i = 0; i < length; i++) {
			for (Model model : rows) {
				Object newValue = ((Map)CacheKit.get(dictCache, dictClasses[i])).get(model.get(keys[i]));
				model.put(newKeys[i], newValue);
			}
		}
		return page;
	}
	
	public static Page<? extends Model> replaceDict(Page<? extends Model> page, String key, String newKey, Class dictClass) {
		List<Model> rows = (List<Model>) page.getList();
		for (Model model : rows) {
			Object newValue = ((Map)CacheKit.get(dictCache, dictClass)).get(model.get(key));
			model.put(newKey, newValue);
		}
		return page;
	}
	
	/**
	 * 缓存数据字典
	 */
	public static void cacheDicts(Class...classes){
		for (Class clazz : classes) {
			List<Record> records = Db.find(SqlKit.sql(clazz));
			Map<String,String> dictMap = Maps.newHashMap();
			for (Record record : records) {
				dictMap.put(record.getStr("xh"), record.getStr("mc"));
			}
			CacheKit.put(dictCache, clazz, dictMap);
		}
	}

}
